package com.lanyou.esb.cook.proxy.service.push.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import com.lanyou.esb.cook.proxy.dao.impl.IfAlarmDao;
import com.lanyou.esb.cook.proxy.entity.IfAlarm;
import com.lanyou.esb.cook.proxy.entity.IfAlarmWorkOrder;
import com.lanyou.esb.cook.proxy.redis.proxy.impl.IfAlarmJedisProxy;
import com.lanyou.esb.cook.proxy.service.IfAlarmWorkOrderService;
import com.lanyou.esb.cook.proxy.service.push.Push;

/**
 * 接口告警消息推送服务
 * 
 * @author Davey.wu
 */
public class IfAlarmPushImpl extends BasePush<IfAlarm> implements Push<IfAlarm> {

	/** Redis代理接口 **/
	private IfAlarmJedisProxy jedisProxy;
	/** 接口告警工单处理接口 **/
	private IfAlarmWorkOrderService ifAlarmWorkOrderService;

	@Override
	public void pushToDB() {
		synchronized (COLLECTION_4_DB) {
			if (COLLECTION_4_DB.size() <= 0) {
				return;
			}
			final List<IfAlarm> alarms = new ArrayList<>(COLLECTION_4_DB.size());
			IfAlarm ifAlarm = null;
			do {
				ifAlarm = COLLECTION_4_DB.poll();
				if (ifAlarm == null) {
					break;
				}
				alarms.add(ifAlarm);
			} while (ifAlarm != null);
			if (alarms.isEmpty()) {
				return;
			}
			try {
				final List<IfAlarmWorkOrder> orders = new ArrayList<>(
						alarms.size());
				IfAlarmWorkOrder order = null;
				// 生成工单
				for (IfAlarm alarm : alarms) {
					order = alarm.getOrder();
					// 根据告警信息生成工单
					if (order == null) {
						order = ifAlarmWorkOrderService
								.generateWorkOrder(alarm);
						// 根据工单编码关联工单
						alarm.setAssignWorkCode(order.getCode());
						alarm.setOrder(order);
					}
					orders.add(order);
				}
				// 对告警信息及工单的保存使用事务管理，告警和工单必须同时保存
				try {
					TransactionTemplate tt = new TransactionTemplate(
							((IfAlarmDao) this.getDao())
									.getTransactionManager());
					tt.execute(new TransactionCallback() {
						public Object doInTransaction(TransactionStatus status) {
							// 保存告警信息
							IfAlarmPushImpl.this.getDao().saveAll(alarms);
							// 保存工单
							ifAlarmWorkOrderService.save(orders);
							return status;
						}
					});
				} catch (Exception e) {
					throw e;
				}
			} catch (Exception e) {
				// 保存失败，将告警信息加入消息队列，用定时任务去尝试推送到DB
				putToCollection4DB(alarms);
			}

		}

	}

	@Override
	public void pushToRedis(IfAlarm alarm) throws Exception {
		if (alarm == null) {
			return;
		}
		// 保存告警信息到REDIS
		jedisProxy.rpush(jedisProxy.getKey(), alarm);
	}

	public IfAlarmJedisProxy getJedisProxy() {
		return jedisProxy;
	}

	public void setJedisProxy(IfAlarmJedisProxy jedisProxy) {
		this.jedisProxy = jedisProxy;
	}

}
